<template>
  <div class="project">
    <div class="trees">
      <!-- 添加一个隐藏的文件选择输入框 -->

      <a-tree
        v-model:selectedKeys="selectedKeys"
        v-if="treeData && treeData.length > 0"
        :tree-data="treeData"
        class="tree"
        show-icon
        draggable
        default-expand-all
        @contextmenu.prevent="showContextMenu($event)"
        @select="onSelect"
      >
        <!-- 自定义展开/折叠图标 -->
        <template #switcherIcon="{ isLeaf, expanded }">
          <span v-if="!isLeaf">
            <DownOutlined v-if="expanded" />
            <RightOutlined v-else />
          </span>
        </template>
        <!--  <template #switcherIcon="{ switcherCls }"><down-outlined :class="switcherCls" /></template> -->
        <template #icon="{ key, selected, type, title, scope }">
          <template v-if="type === 'folder'">
            <SvgIcon name="text" />
          </template>
          <!--  <template v-else-if="key === '0-0-0'">
        <smile-outlined />
      </template> -->
          <template v-else>
            <SvgIcon v-if="getFileExtension(title) === 'jpg' || getFileExtension(title) === 'png'" name="image" />
            <SvgIcon v-else-if="getFileExtension(title) === 'mp4'" name="mp4" />
            <SvgIcon v-else-if="getFileExtension(title) === 'pdf'" name="pdf" />
            <SvgIcon v-else name="txt" />
          </template>
        </template>
        <template #title="{ title, key }">
          <div v-if="editingKey === key" class="editable-title">
            <input v-model="editingTitle" @blur="saveEditing(key)" @keyup.enter="saveEditing(key)" ref="inputRef" />
          </div>
          <div v-else @dblclick="startEditing(key, title)">{{ title }}</div>
        </template>
      </a-tree>

      <!-- 右键菜单 -->
      <ul
        v-if="menuVisible"
        :style="{
          top: menuPosition.y + 'px',
          left: menuPosition.x + 'px',
          position: 'absolute',
          listStyle: 'none',
          padding: '8px',
          background: '#fff',
          border: '1px solid #d9d9d9',
          boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
        }"
      >
        <li @click="handleCreateFile()" style="padding: 4px 8px; cursor: pointer">新建文件</li>
        <li @click="handleCreateFolder()" style="padding: 4px 8px; cursor: pointer">新建文件夹</li>
        <li @click="del()" style="padding: 4px 8px; cursor: pointer">删除</li>
        <li @click="renames()" style="padding: 4px 8px; cursor: pointer">重命名</li>
      </ul>
    </div>
    <div class="content">
      <template v-if="isImageFile">
        <ImageEditor :imageContent="currentImageContent" @update:imageContent="handleImageUpdate" />
      </template>
      <template v-else-if="isVideoFile">
        <VideoPlayer :videoUrl="currentVideo" />
      </template>
      <template v-else-if="isPyFile">
        <PCharms :codes="currentFileContent" @localcode-update="handleLocalCodeUpdate" />
      </template>
      <template v-else>
        <PCharms :codes="currentFileContent" @localcode-update="handleLocalCodeUpdate" />
      </template>
    </div>
    <div class="ai">
      <AiChat></AiChat>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import PCharms from './components/PyCharm.vue';
  import axios from 'axios';
  import { RightOutlined, DownOutlined } from '@ant-design/icons-vue';
  import VideoPlayer from './components/videoPlayer.vue';
  import ImageEditor from './components/ImageEditor.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { uploadFileProject } from './myProject.api';
  import { onMounted, ref, computed, watch, nextTick } from 'vue';
  import { projectlist, fileReader, rename, queryByPath, fileWrite, addPath, deletePath, test } from './myProject.api';
  import AiChat from '/@/components/jeecg/AiChat/index.vue';
  import { SvgIcon } from '/@/components/Icon';
  /*  const imageContent = ref(
    'https://ts1.tc.mm.bing.net/th/id/R-C.7d171db3d5e4715470332922ae1e2622?rik=ksUKRpcEYpBR8w&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50000%2f8606.jpg_wh1200.jpg&ehk=jLHx5b3kslxDSEGzmtVL2P30uk2vYjzOP1cub86g7T8%3d&risl=&pid=ImgRaw&r=0'
  ); */
  const treeData = ref([]);
  const currentVideo = ref(
    'https://vdept3.bdstatic.com/mda-qgvdrk2jx77jkjvv/cae_h264/1722332857707850225/mda-qgvdrk2jx77jkjvv.mp4?v_from_s=hkapp-haokan-suzhou&auth_key=1746372577-0-0-c4a0bca1847a2983f95376281e31b44a&bcevod_channel=searchbox_feed&pd=1&cr=0&cd=0&pt=3&logid=1777452248&vid=3403241032295636835&klogid=1777452248&abtest='
  );
  const editingKey = ref<string | null>(null); // 当前编辑的节点 key
  const editingTitle = ref('');
  const projctPath = ref('');
  const inputRef = ref<HTMLInputElement | null>(null);

  // 当前选中的文件路径和内容
  const currentFileName = ref('');
  const currentFileContent = ref('');
  const currentImageContent = ref('');
  const { notification, createMessage } = useMessage();
  // @dblclick="({ key, title }) => editingKey?.value !== key && startEditing(key, title)"
  onMounted(() => {
    getProjectList();
  });

  const getProjectList = async () => {
    try {
      const res = await queryByPath();
      console.log(res, 'projectlist');

      treeData.value = res;
      console.log(projctPath.value, 'projectPath');
    } catch (error) {}
  };

  const originName = ref('');
  const isNewFile = ref(false);
  const menuVisible = ref(false);
  const menuPosition = ref({ x: 0, y: 0 });
  const menuParent = ref<{ id: number; type: string; children?: any[] } | null>(null);
  const selectedKeys = ref(['0-0']);
  const isNewFolder = ref(false);
  let currentParentKey = ref<string | null>(null); // 用于记录右键点击的节点
  const handleImageUpdate = (data) => {
    console.log(data, 'data111');
  };
  const findNodeByKey = (nodes, key) => {
    if (!Array.isArray(nodes)) {
      console.warn('nodes is not an array:', nodes); // 打印警告信息，方便调试
      return null;
    }
    for (const node of nodes) {
      if (node.key === key) {
        return node;
      }
      if (node.children) {
        const found = findNodeByKey(node.children, key);
        if (found) {
          return found;
        }
      }
    }
    return null;
  };
  const handleLocalCodeUpdate = async (data) => {
    currentFileContent.value = data;
    const path = getCurrentFilePath();
    const lastSlashIndex = path.lastIndexOf('/');
    const directoryPath = lastSlashIndex !== -1 ? path.substring(0, lastSlashIndex) : path;
    try {
      const res = await fileWrite({ fileName: currentFileName.value, filePath: directoryPath, content: currentFileContent.value });
      console.log(res, 'res');
    } catch (error) {
      console.log(error, '写入失败');
    }
  };
  const onSelect = async (selectedKeys, { node }) => {
    console.log(node, 'node111');
    const ext = getFileExtension(node.title);
    // 确保是文件类型
    if (node.type === 'file') {
      const path = getCurrentFilePath();

      currentFileName.value = node.title;
      const filePath = `${import.meta.env.VITE_GLOB_FILE_READER_PREFIX}${path}`;
      console.log(filePath, 'filePath');

      try {
        const res = await fileReader(filePath);
        console.log(res, 'res');

        if (ext === 'py' || ext === 'txt') {
          currentFileContent.value = res;
          console.log(currentFileContent.value, 'currentFileContent');
        } else if (ext === 'jpg' || ext === 'png') {
          // 确保是有效的二进制数据
          if (!(res instanceof Blob) && !(res instanceof Uint8Array)) {
            throw new Error('无效的文件数据格式');
          }
          const blob = new Blob([res], { type: `image/${ext}` });
          const reader = new FileReader();
          reader.onloadend = () => {
            currentImageContent.value = reader.result as string;
            console.log(currentImageContent.value, 'imageContent');
          };
          reader.readAsDataURL(blob);
        }
      } catch (error) {
        console.error('获取文件内容失败:', error);
        currentFileContent.value = '加载文件内容失败';
      }
    } else {
      // 如果不是文件，清空内容
      currentFileName.value = '';
      currentFileContent.value = '';
    }
  };
  const getFileExtension = (filename) => {
    if (!filename) return '';
    return filename.split('.').pop()?.toLowerCase() || '';
  };
  // 判断是否是图片文件
  const isImageFile = computed(() => {
    if (!currentFileName.value) return false;
    const extension = getFileExtension(currentFileName.value);
    return extension === 'jpg' || extension === 'png';
  });
  const isPyFile = computed(() => {
    if (!currentFileName.value) return false;
    const extension = getFileExtension(currentFileName.value);
    return extension === 'py';
  });
  const isVideoFile = computed(() => {
    if (!currentFileName.value) return false;
    const extension = getFileExtension(currentFileName.value);
    return extension === 'mp4';
  });
  const addFolderToNode = (node, newFolder) => {
    if (!node.children) {
      node.children = [];
    }
    node.children.push(newFolder);
  };
  const showContextMenu = (event) => {
    console.log(event, 'event');
    const targetKey = selectedKeys.value[0]; // 假设右键时选中的节点是当前选中的节点
    console.log('右键点击的节点 key:', targetKey);
    menuVisible.value = true;
    menuPosition.value = { x: event.layerX + 30, y: event.layerY };
    //menuParent.value = parent;
    // 添加全局点击事件，点击其他地方时隐藏菜单
    currentParentKey.value = selectedKeys.value[0]; // 假设右键当前选中的节点 // 记录右键点击的节点 key
    document.addEventListener('click', hideContextMenu);
  };

  const hideContextMenu = () => {
    menuVisible.value = false;
    document.removeEventListener('click', hideContextMenu);
  };

  const handleCreateFile = () => {
    console.log('新建文件');

    if (!currentParentKey.value) {
      hideContextMenu();
      return;
    }

    // 查找父节点
    const parentNode = findNodeByKey(treeData.value, currentParentKey.value);
    console.log('parentNode', parentNode);
    // 检查节点是否存在以及类型是否为 folder
    if (parentNode && parentNode.type === 'folder') {
      const newFile = { title: '', key: `file_${Date.now()}_${Math.random()}`, type: 'file' };
      if (!parentNode.children) {
        parentNode.children = [];
      }
      parentNode.children.push(newFile);
      treeData.value = JSON.parse(JSON.stringify(treeData.value));
      isNewFile.value = true; // 标记为新建文件
      startEditing(newFile.key, newFile.title); // 深拷贝触发响应式更新
    } else {
      console.warn('只能在文件夹下创建文件');
    }

    hideContextMenu();
  };

  watch(selectedKeys, (newValue) => {
    console.log('selectedKeys 更新:', newValue);
    selectedKeys.value = newValue;
  });
  const handleCreateFolder = () => {
    console.log(currentParentKey.value, 'currentParentKey.value');
    if (!currentParentKey.value) {
      hideContextMenu();
      return;
    }

    const parentNode = findNodeByKey(treeData.value, currentParentKey.value);
    console.log(parentNode, 'parentNode');
    // 检查节点是否存在以及类型是否为 folder
    if (parentNode && parentNode.type === 'folder') {
      const newFolder = { title: '新建文件夹', key: `folder_${Date.now()}_${Math.random()}`, type: 'folder' };
      if (!parentNode.children) {
        parentNode.children = [];
      }
      parentNode.children.push(newFolder);
      treeData.value = JSON.parse(JSON.stringify(treeData.value));
      isNewFolder.value = true;
      console.log(treeData.value, 'treeData.value');
      startEditing(newFolder.key, newFolder.title); // 立即进入编辑状态 // 深拷贝触发响应式更新
    } else {
      console.warn('只能在文件夹下创建文件夹');
    }

    hideContextMenu();
  };
  // 双击开始编辑
  const startEditing = (key?, title?) => {
    editingKey.value = key;
    editingTitle.value = title;

    // 等待 DOM 更新后自动聚焦输入框
    nextTick(() => {
      if (inputRef.value) {
        inputRef.value.focus();
        inputRef.value.setSelectionRange(title.length, title.length); // 将光标移动到文本末尾
      }
    });
  };

  // 停止编辑
  const stopEditing = () => {
    editingKey.value = null;
    editingTitle.value = '';
  };

  // 双击节点触发编辑
  const handleDblClick = ({ key, title }) => {
    console.log(key, title);
    if (editingKey.value.includes(key)) return; // 如果已在编辑中，则不重复触发
    startEditing(key, title);
  };
  // 判断当前是否为重命名操作
  const isRenaming = (key) => {
    const node = findNodeByKey(treeData.value, key);
    return !!node; // 如果节点存在，说明是重命名；否则是新建
  };
  // 处理文件选择
  const handleFileUpload = (event: Event) => {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      selectedFile.value = input.files[0];
      console.log('已选择文件:', selectedFile.value.name);
    }
  };
  // 保存编辑

  const saveEditing = async (key) => {
    const node = findNodeByKey(treeData.value, key);
    if (!node) {
      console.warn('未找到节点');
      return;
    }

    const newTitle = editingTitle.value.trim();
    console.log(newTitle, 'newTitle');
    if (!newTitle) {
      //  createMessage.error('文件名不能为空');
      return;
    }

    // 如果是新建节点，则调用 addPath 接口
    if (isNewFolder.value) {
      try {
        console.log('addjiekou');

        const path = getCurrentFilePath();
        // const parentPath = getFilePathByKey(treeData.value, currentParentKey.value) || ''; // 获取父节点路径
        const fullPath = `${path}/${newTitle}`;
        const res = await addPath({ projectPath: fullPath }); // 调用新建接口
        console.log(res, '新建成功');

        // 更新本地树数据
        node.title = newTitle; // 设置新名称

        treeData.value = JSON.parse(JSON.stringify(treeData.value)); // 深拷贝触发响应式
        isNewFolder.value = false;
      } catch (error) {
        console.error('新建失败', error);
        createMessage.error('新建失败，请重试');
      }
    } else if (isNewFile.value) {
      console.log('新建文件333');
      if (fileInput.value) {
        fileInput.value.click();
      }
      try {
        const path = getCurrentFilePath();
        // const parentPath = getFilePathByKey(treeData.value, currentParentKey.value) || ''; // 获取父节点路径
        const fullPath = `${path}/${newTitle}`;
        console.log('isnewfile', fullPath);
        // 调用上传文件接口
        const res = await uploadFileProject({ route: fullPath, file: 1 });
        console.log(res, '上传成功');
        // 更新本地树数据
        node.title = newTitle; // 设置新名称

        treeData.value = JSON.parse(JSON.stringify(treeData.value)); // 深拷贝触发响应式
        isNewFile.value = false;
      } catch (error) {
        console.log(error);
      }
    } else {
      // 如果是重命名，则调用 rename 接口
      try {
        console.log('重命名');
        const oldTitle = node.title; // 保存旧名称

        const path = getFilePathByKey(treeData.value, currentParentKey.value); // 获取当前路径
        if (!path) {
          console.warn('未找到节点路径');
          return;
        }

        const res1 = await rename(path, oldTitle, newTitle);

        console.log(res1, '重命名成功');

        // 更新本地树数据
        node.title = newTitle; // 设置新名称
        treeData.value = JSON.parse(JSON.stringify(treeData.value)); // 深拷贝触发响应式
      } catch (error) {
        // console.error('重命名失败', error);
        createMessage.error('重命名失败，请重试');
      }
    }

    // 停止编辑
    stopEditing();
  };

  // 失去焦点保存
  const handleBlur = () => {
    const key = editingKey?.value[0];
    if (key) saveEditing(key);
  };
  // 删除节点（递归删除子节点）
  const deleteNodeByKey = (nodes, key) => {
    if (!Array.isArray(nodes)) return null;
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].key === key) {
        // 找到节点，删除它
        nodes.splice(i, 1);
        return true; // 标记已删除
      }
      if (nodes[i].children) {
        const deleted = deleteNodeByKey(nodes[i].children, key);
        if (deleted) return true; // 如果子节点中删除了，则停止继续搜索
      }
    }
    return false;
  };
  // 删除节点
  const del = async () => {
    if (!currentParentKey.value) {
      console.warn('未选择要删除的节点');
      hideContextMenu();
      return;
    }

    const nodePath = getFilePathByKey(treeData.value, currentParentKey.value); // 获取右键点击节点的路径
    console.log('删除的节点路径:', nodePath);
    if (!nodePath) {
      console.warn('未找到要删除的节点路径');
      hideContextMenu();
      return;
    }
    // 查找节点本身（用于判断是文件还是文件夹）
    const node = findNodeByKey(treeData.value, currentParentKey.value); // 假设你有一个 findNodeByKey 函数
    if (!node) {
      console.warn('未找到要删除的节点');
      hideContextMenu();
      return;
    }
    // 判断是文件还是文件夹
    let finalPath = nodePath; // 创建副本
    if (node.type === 'file') {
      console.log(`即将删除文件: ${finalPath}`);
    } else if (node.type === 'folder') {
      finalPath = `${finalPath}/`;
    } else {
      console.warn('未知节点类型');
      hideContextMenu();
      return;
    }
    try {
      console.log(`即将删除路径: ${finalPath}`);
      const res = await deletePath(finalPath);
      console.log(res, 'deletePath');
      // 删除本地节点
      const deleted = deleteNodeByKey(treeData.value, currentParentKey.value);
      if (deleted) {
        treeData.value = JSON.parse(JSON.stringify(treeData.value)); // 深拷贝触发响应式更新
        console.log(`节点 ${currentParentKey.value} 已删除`);
        getProjectList();
      } else {
        console.warn('未找到要删除的节点');
      }
    } catch (error) {
      console.log('删除失败', error);
    } finally {
      hideContextMenu();
    }
  };
  // 根据 key 找到节点的完整路径
  const getFilePathByKey = (nodes, key, currentPath = '') => {
    for (const node of nodes) {
      const newPath = currentPath ? `${currentPath}/${node.title}` : node.title; // 拼接路径
      if (node.key === key) {
        return newPath; // 找到目标节点，返回路径
      }
      if (node.children) {
        const result = getFilePathByKey(node.children, key, newPath); // 递归查找子节点
        if (result) {
          return result;
        }
      }
    }
    return null; // 未找到目标节点
  };
  const getCurrentFilePath = () => {
    if (selectedKeys.value.length > 0) {
      const path = getFilePathByKey(treeData.value, selectedKeys.value[0]);
      console.log('当前文件路径:', path);
      return path;
    }
    console.warn('未选择任何节点');
    return null;
  };
  // 重命名节点
  const renames = async () => {
    if (!currentParentKey.value) {
      console.warn('未选择要重命名的节点');
      hideContextMenu();
      return;
    }

    // 查找当前右键点击的节点
    const node = findNodeByKey(treeData.value, currentParentKey.value);
    if (!node) {
      console.warn('未找到要重命名的节点');
      hideContextMenu();
      return;
    }

    // 检查节点类型
    if (node.type === 'folder') {
      console.warn('文件夹类型不支持重命名');
      createMessage.warn('文件夹类型不支持重命名');

      hideContextMenu();
      return;
    }

    if (node.type === 'file') {
      console.log('开始重命名文件:', node.title);

      // 进入编辑模式
      startEditing(node.key, node.title);

      // 保存逻辑（在 saveEditing 中处理）
      hideContextMenu();
    }
  };
</script>

<style lang="less" scoped>
  .content {
    // position: fixed;
    // top: 8%;
    width: 40vw;
    // // left: 30%;
    // margin-left: 20px;
    // border-left: 1px solid #eee;
    // border-right: 1px solid #eee;
    height: 100%;
    :deep(.CodeMirror-gutter.CodeMirror-linenumbers) {
      background: #e8f2ff;
    }
  }
  :deep(.ant-tree-node-content-wrapper) {
    display: flex;

    width: 100%;
  }
  .project {
    display: flex;
    height: calc(100vh - 110px);
    overflow-y: hidden;
  }
  .trees {
    min-width: 400px;
    height: 100%;

    :deep(.ant-tree) {
      width: 100%;
      height: 100%;

      margin-right: 10px;
    }
  }
  .ai {
    flex: 1;
  }
</style>
<style lang="less"></style>
